<template>
  <div class="make-course-chapter">
    <div class="header">
      <div class="search">
        <span>关键词：</span>
        <el-input v-model="searchInput" style="width: 200px" clearable />
        <el-button @click="searchChapter()">搜索</el-button>
      </div>
      <div class="btns">
        <el-button @click="addChapter()">新增章节</el-button>
        <el-button @click="openImportDialog()">章节导入</el-button>
        <el-button @click="batchDelete()">批量删除</el-button>
        <el-button @click="adjustOrder()">调整顺序</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="chapter-list">
      <el-table
        ref="multipleTableRef"
        :data="tableData"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          type="index"
          label="序号"
          width="80"
          :index="calculateIndex"
        />
        <el-table-column
          property="name"
          label="章节名称"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column property="sourceType" label="章节来源" min-width="150">
          <template #default="scope">
            <span>{{
              scope.row.sourceType === 1 ? "个人创建" : "智能创建"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column property="typeName" label="章节类型" min-width="120" />
        <!-- <el-table-column
          property="introduction"
          label="章节简介"
          width="350"
          show-overflow-tooltip
        /> -->
        <el-table-column align="center" label="操作" min-width="200">
          <template #default="scope">
            <el-button
              size="small"
              text
              type="primary"
              @click="editChapter(scope.$index, scope.row)"
              style="color: #457aff; font-size: 14px"
            >
              修改
            </el-button>
            <el-button
              style="margin-left: 0px; color: #457aff; font-size: 14px"
              text
              type="primary"
              size="small"
              @click="handleBuild(scope.$index, scope.row)"
            >
              智能搭建
            </el-button>
            <el-tooltip
              class="item"
              effect="dark"
              :content="
                scope.row.falg == 0
                  ? '点击关闭学生章节显示'
                  : '点击开启学生章节显示'
              "
              placement="bottom"
            >
              <el-switch
                style="margin-left: 10px"
                :model-value="scope.row.falg == 0 ? true : false"
                :width="28"
                active-color="#1ac48a"
                @change="
                  changeSwitch(scope.row.courseId, scope.row.id, scope.row.falg)
                "
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑章节 -->
    <el-dialog
      v-model="addOrEditDialog"
      width="35%"
      class="addOrEditDialog"
      :close-on-click-modal="false"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="章节名称" prop="chapterName">
          <el-input
            v-model="form.chapterName"
            placeholder="请输入章节名称"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="章节类型" prop="chapterType">
          <el-select v-model="form.chapterType" placeholder="请选择章节类型">
            <el-option label="理论课" value="理论课"></el-option>
            <el-option label="实验课" value="实验课"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节简介" prop="chapterIntr">
          <el-input
            maxlength="100"
            show-word-limit
            type="textarea"
            v-model="form.chapterIntr"
            placeholder="请输入章节简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="saveChapter()"> 保存 </el-button>
          <el-button @click="addOrEditDialog = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 调整顺序弹窗 -->
    <el-dialog
      v-model="showAdjustOrder"
      width="30%"
      class="addOrEditDialog"
      :close-on-click-modal="false"
    >
      <el-tree
        ref="dragTree"
        :data="treeData"
        :props="defaultProps"
        draggable
        :allow-drop="allowDrop"
        :allow-drag="allowDrag"
        node-key="id"
        default-expand-all
      >
        <template #default="{ data }">
          <span class="custom-tree-node">
            <span>{{ data.label }}</span>
          </span>
        </template>
      </el-tree>
      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="saveOrder()"> 保存 </el-button>
          <el-button @click="showAdjustOrder = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 章节导入 -->
    <el-dialog
      v-model="importChapter"
      width="40%"
      class="import-chapter"
      :close-on-click-modal="false"
      center
    >
      <div class="import-content">
        <el-tabs v-model="activeTab" class="import-tabs">
          <el-tab-pane label="预置课程" name="preset"></el-tab-pane>
          <el-tab-pane label="自定义课程" name="custom"></el-tab-pane>
        </el-tabs>

        <div class="search-box">
          <el-input
            v-model="importSearchInput"
            placeholder="请输入关键字进行过滤"
            style="width: 100%"
          />
        </div>

        <div class="chapter-tree-container">
          <!-- 预置课程选项卡内容 -->
          <div v-if="activeTab === 'preset'">
            <el-tree
              v-if="presetChapters && presetChapters.length > 0"
              ref="importTree"
              :data="presetChapters"
              :props="importTreeProps"
              :filter-node-method="filterNode"
              show-checkbox
              node-key="id"
              default-expand-all
              class="chapter-tree"
            >
              <template #default="{ data }">
                <span class="custom-tree-node">
                  <span>{{ data.label }}</span>
                </span>
              </template>
            </el-tree>
            <div v-else class="no-data">
              <span>暂无数据</span>
            </div>
          </div>

          <!-- 自定义课程选项卡内容 -->
          <div v-if="activeTab === 'custom'">
            <el-tree
              v-if="customChapters && customChapters.length > 0"
              ref="customTree"
              :data="customChapters"
              :props="customTreeProps"
              :filter-node-method="filterNode"
              show-checkbox
              node-key="id"
              default-expand-all
              class="chapter-tree"
            >
              <template #default="{ data }">
                <span class="custom-tree-node">
                  <span>{{ data.label }}</span>
                </span>
              </template>
            </el-tree>
            <div v-else class="no-data">
              <span>暂无数据</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="saveImport()">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      courseId: "",
      searchInput: "",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      addOrEditDialog: false,
      showAdjustOrder: false,
      importChapter: false,
      isEdit: false,
      selectIds: [],
      form: {
        chapterName: "",
        chapterType: "",
        chapterIntr: "",
        editId: "",
      },
      rules: {
        chapterName: [
          { required: true, message: "请输入章节名称", trigger: "blur" },
        ],
        chapterType: [
          { required: true, message: "请选择章节类型", trigger: "blur" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      tableData: [], // 章节列表
      treeData: [], // 调整顺序树形数据
      importTreeProps: {
        children: "children",
        label: "label",
      },
      customTreeProps: {
        children: "children",
        label: "label",
      },
      activeTab: "preset",
      importSearchInput: "",
      presetChapters: [], // 预置课程章节树
      customChapters: [], // 自定义课程章节树
    };
  },

  watch: {
    importSearchInput: _.debounce(function (val) {
      if (this.activeTab == "preset") {
        this.$refs.importTree.filter(val);
      }

      if (this.activeTab == "custom") {
        this.$refs.customTree.filter(val);
      }
    }, 1000),
  },

  created() {
    this.courseId = localStorage.getItem("courseId");
    this.getChapterList();
  },

  methods: {
    // 计算表格序号
    calculateIndex(index) {
      return (this.currentPage - 1) * this.pageSize + index + 1;
    },
    // 搜索章节
    searchChapter() {
      this.currentPage = 1;
      this.getChapterList();
    },
    // 获取章节列表
    getChapterList() {
      this.$axios
        .post(
          `/tes/course/${this.courseId}/chapter/list/owner-search?pageSize=${this.pageSize}&pageNum=${this.currentPage}`,
          {
            name: this.searchInput,
          }
        )
        .then((res) => {
          this.tableData = res.data.content;
          this.total = res.data.total;
        });
    },
    handleSelectionChange(val) {
      this.selectIds = val.map((item) => item.id);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getChapterList();
    },

    // 智能搭建
    handleBuild(index, row) {
      console.log(row);

      this.$router.push({
        path: "/aiTeaching/courseBuild/makeCourseChapterBuild",
        query: { id: row.id, name: row.name },
      });
    },

    // 新增章节
    addChapter() {
      this.isEdit = false;
      this.addOrEditDialog = true;
      this.form = {
        chapterName: "",
        chapterType: "",
        chapterIntr: "",
      };
    },

    // 修改章节
    editChapter(index, row) {
      this.isEdit = true;
      this.addOrEditDialog = true;
      this.form = {
        chapterName: row.name,
        chapterType: row.typeName,
        chapterIntr: row.introduction,
        editId: row.id,
      };
    },

    // 批量删除
    batchDelete() {
      if (this.selectIds.length === 0) {
        this.$message.warning("请选择要删除的章节");
        return;
      }
      this.$confirm("确定删除所选章节吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .post(
            `/tes/course/${this.courseId}/chapter/batch-delete`,
            this.selectIds
          )
          .then((res) => {
            this.getChapterList();
            this.$message.success("删除成功");
            this.$refs.multipleTableRef.clearSelection();
            // 如果当前页没有数据了，回到上一页
            const maxPage = Math.ceil(this.total / this.pageSize);
            if (this.currentPage > maxPage && maxPage > 0) {
              this.currentPage = maxPage;
            }
          });
      });
    },

    // 保存新增/编辑章节
    saveChapter() {
      let queryObj = {};
      if (!this.isEdit) {
        queryObj = {
          introduction: this.form.chapterIntr,
          name: this.form.chapterName,
          typeName: this.form.chapterType,
          technologyIdList: [],
          stepTypeStr: "",
        };
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$axios
              .post(`/tes/course/${this.courseId}/chapter`, queryObj)
              .then((res) => {
                this.getChapterList();
                this.addOrEditDialog = false;
                this.$message.success("添加成功");
              });
          }
        });
      } else {
        queryObj = {
          introduction: this.form.chapterIntr,
          name: this.form.chapterName,
          typeName: this.form.chapterType,
          technologyIdList: [],
          stepTypeStr: "",
        };
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$axios
              .put(
                `/tes/course/${this.courseId}/chapter/${this.form.editId}`,
                queryObj
              )
              .then((res) => {
                this.getChapterList();
                this.addOrEditDialog = false;
                this.$message.success("修改成功");
              });
          }
        });
      }
    },

    // 调整顺序
    adjustOrder() {
      this.getTreeData();
      this.showAdjustOrder = true;
    },

    // 获取调整顺序树形数据
    getTreeData() {
      this.$axios
        .get(`/tes/course/${this.courseId}/chapter/ztree`)
        .then((res) => {
          this.treeData = res.data;
        });
    },

    // 保存调整顺序
    saveOrder() {
      const latestTreeData = this.$refs.dragTree
        ? this.$refs.dragTree.data
        : this.treeData;
      const chapterIdList = latestTreeData[0].children.map((item) => item.id);
      this.$axios
        .post(
          `/tes/course/${this.courseId}/chapter/order-adjustments`,
          chapterIdList
        )
        .then((res) => {
          this.getChapterList();
          this.$message.success("调整顺序成功");
        });
      this.showAdjustOrder = false;
    },

    allowDrop(draggingNode, dropNode, type) {
      // 只允许同级别节点拖拽
      return type === "inner" ? false : true;
    },
    allowDrag() {
      return true;
    },

    // 章节导入
    openImportDialog() {
      this.presetChapters = [];
      this.customChapters = [];
      this.importSearchInput = "";
      this.$axios
        .get(`/tes/course/${this.courseId}/ztree?type=1`)
        .then((res) => {
          this.presetChapters = res.data;
        });
      this.$axios
        .get(`/tes/course/${this.courseId}/ztree?type=0`)
        .then((res) => {
          this.customChapters = res.data;
        });
      this.importChapter = true;
    },

    // 保存导入
    saveImport() {
      if (this.activeTab == "preset" && this.presetChapters.length === 0) {
        this.$message.warning("暂无预置课程");
        return;
      }
      if (this.activeTab == "custom" && this.customChapters.length === 0) {
        this.$message.warning("暂无自定义课程");
        return;
      }

      const type = this.activeTab == "preset" ? 1 : 0;
      let selectIds = [];
      type == 1
        ? (selectIds = this.$refs.importTree.getCheckedKeys(true))
        : (selectIds = this.$refs.customTree.getCheckedKeys(true));

      if (selectIds.length === 0) {
        this.$message.warning("请选择要导入的章节");
        return;
      }

      const loading = this.$loading({
        lock: true,
        text: "保存中...",
        background: "rgba(0, 0, 0, 0.7)",
      });

      this.$axios
        .post(
          `/tes/course/${this.courseId}/chapter/import-exist?type=${type}`,
          selectIds
        )
        .then((res) => {
          this.getChapterList();
          this.importChapter = false;
          this.$message.success("导入成功");
          loading.close();
        })
        .finally(() => {
          loading.close();
        });
    },

    // 切换章节显示状态
    changeSwitch(courseId, chapterId, currentFlag) {
      const newFlag = currentFlag == 0 ? true : false;
      const queryObj = {
        falg: newFlag,
        type: 0,
      };
      this.$axios
        .put(`/tes/course/${courseId}/chapter/${chapterId}/falg`, queryObj)
        .then(() => {
          this.getChapterList();
        });
    },

    // 树形节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
.make-course-chapter {
  background-color: #fff;
  padding: 40px 50px 40px 70px;
  box-sizing: border-box;
  min-height: 650px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        font-size: 16px;
        color: #252e54;
      }
      .el-button {
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #a5beff;
        color: #457aff;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .el-button {
        background: #457aff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
  .chapter-list {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;

    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
    :deep(.el-switch.is-checked .el-switch__core) {
      background-color: #1ac48a;
      border-color: #1ac48a;
    }
  }
}
</style>

<!-- 弹窗样式 -->
<style lang="scss">
.el-popper.is-dark {
  max-width: 30%;
  line-height: 22px;
}
.addOrEditDialog {
  .el-dialog__body {
    padding: 20px 20px 0 0;
    .el-textarea__inner {
      height: 100px;
    }
    &::-webkit-scrollbar {
      width: 4px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #e5e5e5;
    }
    &::-webkit-scrollbar-track {
      background-color: #f5f5f5;
    }
  }
}

.import-chapter {
  .el-dialog__body {
    padding: 20px;
    max-height: 600px;
    overflow-y: auto;
  }

  .import-content {
    .import-tabs {
      .el-tabs__nav-scroll {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .el-tabs__nav-wrap:after {
        background-color: #fff;
        color: #457aff;
      }
      .el-tabs__active-bar {
        background-color: #457aff;
      }
      .el-tabs__item.is-active,
      .el-tabs__item:hover {
        color: #457aff;
      }
    }

    .search-box {
      margin-bottom: 20px;
      .el-input {
        :deep(.el-input__wrapper) {
          border: 1px solid #dcdfe6;
          &:hover {
            border-color: #155eef;
          }
          &.is-focus {
            border-color: #155eef;
            box-shadow: 0 0 0 2px rgba(69, 122, 255, 0.2);
          }
        }
      }
    }

    .chapter-tree {
      max-height: 400px;
      overflow-y: auto;
      border-radius: 4px;
      padding: 10px;

      &::-webkit-scrollbar {
        width: 6px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #c1c1c1;
        border-radius: 3px;
      }
      &::-webkit-scrollbar-track {
        background-color: #f1f1f1;
      }

      .custom-tree-node {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;

        .chapter-info {
          color: #909399;
          font-size: 12px;
          background: #f0f0f0;
          padding: 2px 8px;
          border-radius: 12px;
        }
      }

      :deep(.el-tree-node__content) {
        height: 40px;
        &:hover {
          background-color: #f5f7fa;
        }
      }

      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
        background-color: #457aff;
        border-color: #457aff;
      }

      :deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
        background-color: #457aff;
        border-color: #457aff;
      }
    }

    .no-data {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100px;
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>